extends TouchScreenButton

const RANGE:=16 # 可拖动半径

var index:=-1 # 手指的序号
var dragOffset:Vector2
@onready var resetPos := global_position

func _input(event: InputEvent) -> void:
    var touch: = event as InputEventScreenTouch

    # 触碰
    if touch:
        if touch.pressed and index==-1:
            var globalPos := touch.position* get_canvas_transform()
            var localPos := globalPos* get_global_transform()
            # 判断坐标在不在矩形中
            var rect:= Rect2(Vector2.ZERO,texture_normal.get_size())
            if rect.has_point(localPos):
                # 按下
                index=touch.index
                dragOffset = globalPos - global_position
        elif not touch.pressed and touch.index == index:
            # 松开
            Input.action_release('move_left')
            Input.action_release('move_right')
            index=-1
            global_position = resetPos

    # 拖拽
    var drag:= event as InputEventScreenDrag
    if drag and drag.index == index:
        # 拖动
        var target =  drag.position*get_canvas_transform()-dragOffset
        var movement:=(target-resetPos).limit_length(RANGE)
        global_position=resetPos+movement

        movement/=RANGE
        if movement.x>0:
            Input.action_release('move_left')
            Input.action_press('move_right',movement.x)
        elif movement.x<0:
            Input.action_release('move_right')
            Input.action_press('move_left',-movement.x)



